// 对比信号量和互斥锁的行为

#include <gtest/gtest.h>
#include <semaphore.h>
#include <thread>
#include <mutex>
#include <atomic>

std::mutex mtx;
std::binary_semaphore sem(1); // 二元信号量

void use_mutex(int id, std::atomic<int>& counter) {
    std::lock_guard<std::mutex> lock(mtx); // 加锁
    ++counter;
    std::this_thread::sleep_for(std::chrono::milliseconds(100)); // 模拟工作
}

void use_semaphore(int id, std::atomic<int>& counter) {
    sem.acquire(); // 获取信号量
    ++counter;
    std::this_thread::sleep_for(std::chrono::milliseconds(100)); // 模拟工作
    sem.release(); // 释放信号量
}

TEST(SemaphoreVsMutexTest, MutexVsSemaphore) {
    std::atomic<int> counter(0);

    std::thread t1(use_mutex, 1, std::ref(counter));
    std::thread t2(use_mutex, 2, std::ref(counter));

    std::thread t3(use_semaphore, 3, std::ref(counter));
    std::thread t4(use_semaphore, 4, std::ref(counter));

    t1.join();
    t2.join();
    t3.join();
    t4.join();

    EXPECT_EQ(counter.load(), 4); // 验证所有线程都正确完成
}